package com.ciwong.epaper.modules.evaluate.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.epaper.adapter.UserDKListAdapter;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.evaluate.bean.UserDKPageBean;
import com.ciwong.epaper.modules.evaluate.bean.UserDkWork;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.i.OnChildClickListener;
import com.ciwong.mobilelib.utils.ToastUtil;
import java.util.ArrayList;
import java.util.List;

public class UserDKListFragment extends BaseFragment implements PullToRefreshView.OnHeaderRefreshListener,
        PullToRefreshView.OnFooterRefreshListener{

    private ExpandableListView user_dk_exlist;

    private UserDKListAdapter userDKListAdapter;

    /**
     * 默认从第一页开始加载
     */
    private final int defult_page = 1;

    private int pageCount;

    /**
     * 当前页码
     */
    private int curPage = defult_page;

    private int mPageCount = -1;

    /**
     * 默认加载数据大小
     */
    private static final int LOAD_PAGE_SIZE = 10;

    /**
     * 是否是刷新状态,true为刷新，false为加载更多
     */
    private boolean isRefresh = true;

    /**
     * 刷新ListView
     */
    private PullToRefreshView mRefreshView;

    private UserDKPageBean userDKPageBean;

    private List<UserDkWork> workList;

    private TextView tv_net_tips, mTvNoDataTips;

    public View mFooterView;

    private RelativeLayout handle_go_to_bookdesk;

    private Boolean hasWork;


    /**
     * 打卡作业列表
     */
    public List<UserDkWork> userDkWorks = new ArrayList<UserDkWork>();

    public void addAll(List<UserDkWork> userDkWorks) {
                    for (UserDkWork userDkWork : workList) {
//                        if (epaperInfo.isAdded()) {
                        workList.add(userDkWork);
//                        }
                    }

            }

    /**
     * 获取打卡作业列表
     */
    public void getUserDkWorks(final int curPage){
        EpaperDao.getInstance().getUserDkWorks(EApplication.BRAND_ID, curPage, LOAD_PAGE_SIZE,new BaseExtCallBack(getActivity(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                mRefreshView.onFooterRefreshComplete();
                mRefreshView.onHeaderRefreshComplete();
                hideCricleProgress();
                super.failed(errorCode, data);
                failed(data);
            }

            @Override
            public void failed(Object data) {
                mRefreshView.onFooterRefreshComplete();
                mRefreshView.onHeaderRefreshComplete();
                if(data instanceof TimeoutError){
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError("加载失败，检查网络重新请求");
                }
            }

            @Override
            public void success(Object data) {
                mRefreshView.onFooterRefreshComplete();
                mRefreshView.onHeaderRefreshComplete();
                hideCricleProgress();
                if (data != null) {
                    userDKPageBean = (UserDKPageBean) data;
                    List<UserDkWork> list =  userDKPageBean.getPageList();
                    pageCount = userDKPageBean.getPageCount();
                    if (list.size() == 0 && pageCount == 0){
                         handle_go_to_bookdesk.setVisibility(View.VISIBLE);
                         mTvNoDataTips.setText("暂无打卡作业");
                     }else {
                         handle_go_to_bookdesk.setVisibility(View.GONE);
                         workList = list;
                         if (curPage == 1) {
                             userDKListAdapter.clear();
                         }
                         if (userDKPageBean.getPageList().size() < 1 && curPage == 1) {
                             //showEmptyView();
                         } else {
                             userDKListAdapter.addAll(userDKPageBean.getPageList());
                             //showNormalView();
                         }
                         for(int i = 0; i < userDKListAdapter.getGroupCount(); i++){
                             user_dk_exlist.expandGroup(i);
                         }
                         if (userDKListAdapter.getGroupCount() == userDKPageBean.getTotalCount()) {
                             mRefreshView.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                         } else {
                             mRefreshView.setFooterState(PullToRefreshView.PULL_TO_REFRESH);
                         }
                     }
                     }

            }
        });
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG);
        //注册广播
        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            if (EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG.equals(intent.getAction())) {
                getUserDkWorks(curPage);
            }
        }
    };



    /**
     * 底部刷新
     *
     * @param view
     */
    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        if (!NetworkUtils.isOnline()) {
            CWToast.makeText(getActivity(), getString(R.string.connect_disable), Toast.LENGTH_LONG).setToastType(CWToast.TOAST_TYPE_ERROR).show();
            return;
        }
        curPage++;
        getUserDkWorks(curPage);
    }

    /**
     * 头部刷新
     *
     * @param view
     */
    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        curPage = 1;
        getUserDkWorks(curPage);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_user_dk_list, container, false);
        findViews(view);
        init();
        initEvent();
        loadData();
        registerBoradcastReceiver();
        return view;
    }



    protected void findViews(View view) {
        mTvNoDataTips = view.findViewById(R.id.dk_tv_no_work_from_teacher_tip);
        handle_go_to_bookdesk = view. findViewById(R.id.dk_handle_go_to_bookdesk);
        user_dk_exlist = view. findViewById(R.id.user_dk_exlist);
        mRefreshView = view.findViewById(R.id.dk_work_refresh_view);
        user_dk_exlist.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });

    }


    protected void initEvent() {
        mRefreshView.setOnHeaderRefreshListener(this);
        mRefreshView.setOnFooterRefreshListener(this);
        user_dk_exlist.setOnChildClickListener(new OnChildClickListener() {
            @Override
            public boolean avertRepeatOnClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
                UserDkWork userDkWork = userDKListAdapter.getUserDkWorks().get(i);
                EpaperJumpManager.jumpToUserDKWorkActivity(mActivity,userDkWork.getWorkId(),R.string.go_back);
                return true;
            }

        });
    }


    protected void init() {
       // loadLocalData(SerializableManager.SerializeKey.SHARE_KEY_USERDKWORK_LIST);
        //setTitleText("打卡作业");
        userDKListAdapter = new UserDKListAdapter(getActivity(),userDkWorks, UserDKListAdapter.ADD_TYPE_NO);
        user_dk_exlist.setAdapter(userDKListAdapter);
        registerBoradcastReceiver();
    }

    protected void loadData() {
        showCricleProgress();
        getUserDkWorks(curPage);
    }

    private void unregisterReceiver() {
        if (mBroadcastReceiver != null)
            getActivity().unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void onDestroy() {
        unregisterReceiver();
        super.onDestroy();
    }

}
